using System;
using UnityEngine;

public class BuildingPlacer : MonoBehaviour
{
    public event Action ActiveBuildableChanged;

    // 当前正在建造的可建造物品
    [field: SerializeField]
    public BuildableItem ActiveBuildable { get; private set; }

    // 最大建造距离
    [SerializeField]
    private float _maxBuildingDistance = 3f;

    // ConstructionLayer组件
    [SerializeField]
    private ConstructionLayer _constructionLayer;
    // 格子位置相关控制 可以通过它 进行坐标转换

    [SerializeField]
    private PreviewLayer _previewLayer;

    private Vector3Int cursorPos;

    // 在每帧更新函数中判断是否建造
    private void Update()
    {
        // 将屏幕上的鼠标位置转换为格子坐标
        cursorPos = _constructionLayer._tilemap.WorldToCell(Camera.main.ScreenToWorldPoint(Input.mousePosition));

        // 如果鼠标不在建造范围内，则退出
        if (!IsMouseWithinBuildableRange())
        {
            //清除建筑预览
            _previewLayer.ClearPreview();
            return;
        }

        
        if(ActiveBuildable == null) return;

        bool isSpaceEmpty = _constructionLayer.IsEmpty(cursorPos, ActiveBuildable.UseCustomCollisionSpace ? ActiveBuildable.CollisionSpace : default);

        //显示建筑物预览
        _previewLayer.ShowPreview(ActiveBuildable, cursorPos, isSpaceEmpty);

        // 如果鼠标左键按下且当前有可建造物品和ConstructionLayer组件，则在鼠标点击的格子坐标上建造可建造物品
        if (Input.GetMouseButtonDown(0) && isSpaceEmpty)
        {
            _constructionLayer.Build(cursorPos, ActiveBuildable);
        }

        //鼠标右键删除建筑
        if(Input.GetMouseButtonDown(1) && _constructionLayer != null){
            _constructionLayer.Destroy(cursorPos);
        }
    }

    // 判断鼠标是否处于建造范围内
    private bool IsMouseWithinBuildableRange()
    {
        // 计算鼠标位置与主角的距离是否小于最大建造距离
        return Vector3.Distance(cursorPos, transform.position) <= _maxBuildingDistance;
    }

    //设置正在建造物品
    public void SetActiveBuildable(BuildableItem item)
    {
        ActiveBuildable = item;
        ActiveBuildableChanged?.Invoke();
    }
}

